package config.graceful;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import util.JsonMapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Slf4j
@Component
public class SelfServerListListener implements ServerListListener {

    @Resource
    private NacosDiscoveryProperties properties;

    private NamingService namingService;

    @PostConstruct
    public void init() {
        namingService = properties.namingServiceInstance();
        log.info("init naming service.....");
    }

    /**
     * 创建监听器
     */
    @Override
    public void listen(String serviceId, ServerEventHandler eventHandler) {
        try {
            namingService.subscribe(serviceId, properties.getGroup(), event -> {
                if (event instanceof NamingEvent) {
                    NamingEvent namingEvent = (NamingEvent) event;
                    log.info("listen event：{}", JsonMapperUtil.getInstance().toJson(event));
                    // 实际更新
                    eventHandler.update();
                }
            });
        } catch (NacosException e) {
            log.error("Nacos exception : {}",e);
        }
    }
}
